<?php

namespace oceanengine;

use Psr\Log\LoggerInterface;
use ShidianUtil\Net\IHttpClient;
use ShidianUtil\Utils\ConvertUtil;
use ShidianUtil\Utils\TimeUtil;

/**
 * 巨量引擎，API回传
 * Class Oceanengine
 * @package oceanengine
 */
class Oceanengine
{
    private $httpClient;
    private $logger;

    /**
     * @param IHttpClient $httpClient
     * @param LoggerInterface $logger
     */
    public function __construct(IHttpClient $httpClient, LoggerInterface $logger)
    {
        $this->httpClient = $httpClient;
        $this->logger = $logger;
    }

    /**
     * API回传
     * @param string $event_type
     * @param string $clickid callback 这里需要填写的就是从启动参数里获取的 clickid
     * @return OceanengineResponse
     */
    public function conversion(string $event_type, string $clickid): OceanengineResponse
    {
        $uri = 'https://analytics.oceanengine.com/api/v2/conversion';

        $post = [
            'event_type' => $event_type,
            'context' => [
                'ad' => [
                    'callback' => $clickid,
                ]
            ],
            'timestamp' => (int)TimeUtil::millitime()
        ];

        $response = $this->httpClient->postJSONFormat($uri, [], [], $post);

        $body = $response->getBody()->__toString();

        if ($response->getStatusCode() != 200) {
            $this->logger->error('巨量引擎API回传HTTP状态码异常，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
            return new OceanengineResponse($response, false, []);
        }

        $data = [];

        try {
            $data = ConvertUtil::jsonDecode($body);

            $code = $data['code'] ?? null;
            if ($code === 0 || $code === '0') {
                $this->logger->info('巨量引擎API回传正常，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
                return new OceanengineResponse($response, true, $data);
            }

            $this->logger->error('巨量引擎API回传接口响应码错误，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
            return new OceanengineResponse($response, false, $data);
        } catch (\Throwable $throwable) {

            $this->logger->error('巨量引擎API回传接口异常，原因{message}', ['message' => $throwable->getMessage()]);
            return new OceanengineResponse($response, false, $data);
        }
    }


}
